package org.linlinjava.litemall.admin.aop;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.linlinjava.litemall.core.exception.ServiceException;
import org.linlinjava.litemall.core.util.IPGeolocation;
import org.linlinjava.litemall.core.util.WeChatBot.WeChatBotUtils;
import org.linlinjava.litemall.db.config.AppConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

@Component
@Aspect
@Slf4j
public class AdminLogAop {
    public static final String WECHAT_FAIL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=331a7ea0-399e-441a-8f61-d079e2eeae69";
    private final AppConfig appConfig;
    @Autowired
    public AdminLogAop(AppConfig appConfig) {
        this.appConfig = appConfig;
    }
    @SneakyThrows
    @AfterThrowing(value = "execution(* org.linlinjava.litemall.admin.controller.*.*(..))", throwing = "exception")
    public void afterThrowing(JoinPoint jp, Exception exception) {
        String name = jp.getSignature().getName();
        log.info(name+"方法抛异常了，异常-> {}", exception.getMessage());

        //如果是断言返回的失败报错就不用发通知
        if(exception instanceof IllegalArgumentException || exception instanceof  ServiceException )return;

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 获取客户端的 IP 地址
        String ipAddress = request.getHeader("X-Real-IP");
        if (ipAddress == null || ipAddress.isEmpty()) {
            ipAddress = request.getHeader("X-Forwarded-For");
        }
        if (ipAddress == null || ipAddress.isEmpty()) {
            ipAddress = request.getRemoteAddr();
        }

        WeChatBotUtils weChatBot = new WeChatBotUtils(WECHAT_FAIL, true);
        String markdownMsg = "Lumiere-BUG警报\n" +
                "    >告警来自：<font color=\"warning\">Admin</font >\n" +
                "    >BUG接口：<font color=\"warning\">"+request.getRequestURI()+"</font>\n" +
                "    >环境来源：<font color=\"warning\">"+appConfig.getSource()+"</font >\n" +
                "    >请求方法名：<font color=\"warning\">"+jp.getSignature().getName()+"</font >\n" +
                "    >请求类型：<font color=\"warning\">"+request.getMethod()+"</font>\n" +
                "    >请求IP：<font color=\"warning\">"+ipAddress+"</font>\n" +
                "    >请求地区：<font color=\"c\">"+ IPGeolocation.getIPGeolocation(ipAddress)+"</font>\n" +
                "    >入　参：<font color=\"warning\">"+ jp.getArgs().toString() +"</font>\n" +
                "    >日　期：<font color=\"warning\">"+ DateUtil.formatDate(DateUtil.date())+"</font>\n" +
                "    >时　间：<font color=\"comment\">"+ DateUtil.format(new Date(), "a")+ DateUtil.formatTime(DateUtil.date())+"</font>\n" +
                "    >BUG信息：<font color=\"info\">"+exception+"</font>\n" +
                ">详细错误：<font color=\"comment\">" + exception.getMessage() + "</font>\n";
        StringWriter sw = new StringWriter();
        exception.printStackTrace(new PrintWriter(sw));
        String stackTrace = sw.toString();
        markdownMsg += ">堆栈信息：\n```\n" + stackTrace + "\n```";
        weChatBot.sendMarKDownMsg(markdownMsg);
    }

}
